<template>
    <div class="category">
      <p class="categoryBox__title">文章目录</p>
      <ul class="categoryBox__list">
          <li v-for="(item, index) in category" :key="item.text"
            :class="['categoryBox__' + item.tagName,{'categoryBoxActive': index===isActive()}]"
            @click="backToIndex(item.height)">
            <span :title="item.text">{{item.text}}</span>
          </li>
      </ul>
    </div>
</template>

<script>
import { mapGetters } from 'vuex'
import throttle from 'common/utils/throttle.js'
export default {
  name: 'category',
  data() {
    return {
      scrollTop: 0
    }
  },
  computed: {
    ...mapGetters([
      'category'
    ])
  },
  created() {
    window.onscroll = throttle(this.getScrollTop, 20)
    // window.onscroll = this.getScrollTop()
  },
  methods: {
    isActive() {
      for (let i = 0, len = this.category.length; i < len; i++) {
        if (this.category[i].height >= this.scrollTop + 10) {
          return i - 1
        }
      }
      return this.category.length - 1
    },
    backToIndex(height) {
      window.scrollTo(0, height)
    },
    getScrollTop() {
      this.scrollTop = document.body.scrollTop || document.documentElement.scrollTop || window.pageYOffset
    }
  },
  beforeDestroy() {
    window.onscroll = null
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
.category {
  user-select: none;
  height: 100%;
  background: rgba(255,255,255,0.5);
  .categoryBox__title {
    margin: 0;
    padding: 5px 10px;
    background: rgba(255,255,255,0.5);
    // border-radius: 3px;
  }
  .categoryBox__list {
    box-sizing: border-box;
    padding: 5px 5px 100px;
    margin: 0;
    height: 100%;
    max-height:600px;
    overflow-y: auto;
    .categoryBoxActive {
      color: red;
    }
    .categoryBox {
      padding-left: 20px;
      padding-right: 15px;
      will-change: transform;
      &__title {
        margin: 0;
        padding: 0 0 10px;
        font-weight: bold;
      }
      &__h1 {
        padding: 3px 0 3px 10px;
      }
      &__h2 {
        padding: 5px 0 5px 20px;
      }
      &__h3 {
        padding: 4px 0 4px 30px;
      }
      &__h4 {
        padding: 2px 0 2px 40px;
      }
      &__h5 {
        padding: 2px 0 2px 50px;
      }
      &__h6 {
        padding-left: 60px;
      }
      &__h1,&__h2,&__h3,&__h4,&__h5,&__h6 {
        cursor: pointer;
        width: 90%;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        &:hover {
          background: rgba(255,255,255,0.5)
        }
      }
    }
  }
}
</style>
